1. echopype Tour

https://github.com/OSOceanAcoustics/echopype-examples/blob/main/notebooks/

A quick tour of core echopype capabilities.

1.1. Exploring ship echosounder data from the Pacific Hake survey

1.1.1. Goals

  • Illustrate a common workflow for echosounder data conversion, calibration and use. This workflow leverages the standardization applied by echopype and the power, ease of use and familiarity of libraries in the scientific Python ecosystem.

  • Extract and visualize data with relative ease.

1.1.2. Description

This notebook uses EK60 echosounder data collected during the 2017 Joint U.S.-Canada Integrated Ecosystem and Pacific Hake Acoustic Trawl Survey (‘Pacific Hake Survey’) to illustrate a common workflow for data conversion, calibration and analysis using echopype and core scientific Python software packages, particularly xarray, GeoPandas and pandas.

Two days of cloud-hosted .raw data files are accessed by echopype directly from an Amazon Web Services (AWS) S3 “bucket” maintained by the NOAA NCEI Water-Column Sonar Data Archive. With echopype, each file is converted to a standardized representation based on the SONAR-netCDF4 v1.0 convention and saved to the netCDF4 files format.

Data stored in the netCDF-based SONAR-netCDF4 convention can be conveniently and intuitively manipulated with xarray in combination with related scientific Python packages. Mean Volume Backscattering Strength (MVBS) is computed with echopype from the combined, converted raw data files. The GPS location track and MVBS echograms are visualized.

1.1.3. Running the notebook

This notebook can be run with a conda environment created using the conda environment file https://github.com/OSOceanAcoustics/echopype-examples/blob/echopype_paper/binder/environment.yml. The notebook creates the ./exports directory, if not already present. netCDF files will be exported there.

import glob
from pathlib import Path

import fsspec
import geopandas as gpd
import xarray as xr

import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.io.img_tiles as cimgt
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
import hvplot.xarray

import echopype as ep

import warnings
warnings.simplefilter("ignore", category=DeprecationWarning)

1.2. Compile list of raw files to read from the NCEI WCSD S3 bucket

We’ll compile a list of several EK60 .raw files from the 2017 Pacific Hake survey, available via open, anonymous access from an AWS S3 bucket managed by the NCEI WCSD.

After using fsspec to establish an S3 “file system” access point, extract a list of .raw files in the target directory.

fs = fsspec.filesystem('s3', anon=True)

bucket = "ncei-wcsd-archive"
rawdirpath = "data/raw/Bell_M._Shimada/SH1707/EK60"
s3rawfiles = fs.glob(f"{bucket}/{rawdirpath}/*.raw")
print(f"There are {len(s3rawfiles)} raw files in the directory")
There are 4343 raw files in the directory
# print out the last two S3 raw file paths in the list
s3rawfiles[-2:]
['ncei-wcsd-archive/data/raw/Bell_M._Shimada/SH1707/EK60/Summer2017-D20170913-T180733.raw',
 'ncei-wcsd-archive/data/raw/Bell_M._Shimada/SH1707/EK60/Winter2017-D20170615-T002629.raw']

Each of these .raw files is typically about 25 MB. To select a reasonably small but meaningful target for this demo, let’s select all files from 2017-07-28 collected over a two hour period, 18:00 to 19:59 UTC. This is done through string matching on the time stamps found in the file names.

s3rawfiles = [
    s3path for s3path in s3rawfiles 
    if any([f"D2017{dtstr}" in s3path for dtstr in ['0728-T18', '0728-T19']])
]

print(f"There are {len(s3rawfiles)} target raw files available")
There are 5 target raw files available
s3rawfiles
['ncei-wcsd-archive/data/raw/Bell_M._Shimada/SH1707/EK60/Summer2017-D20170728-T181619.raw',
 'ncei-wcsd-archive/data/raw/Bell_M._Shimada/SH1707/EK60/Summer2017-D20170728-T184131.raw',
 'ncei-wcsd-archive/data/raw/Bell_M._Shimada/SH1707/EK60/Summer2017-D20170728-T190728.raw',
 'ncei-wcsd-archive/data/raw/Bell_M._Shimada/SH1707/EK60/Summer2017-D20170728-T193459.raw',
 'ncei-wcsd-archive/data/raw/Bell_M._Shimada/SH1707/EK60/Summer2017-D20170728-T195219.raw']

1.3. Read target raw files directly from AWS S3 bucket and convert to netcdf

Create the directory where the exported files will be saved, if this directory doesn’t already exist.

converted_dpath = Path('exports')
converted_dpath.mkdir(exist_ok=True)

EchoData is an echopype object for conveniently handling raw converted data from either raw instrument files or previously converted and standardized raw netCDF4 and Zarr files. It is essentially a container for multiple xarray.Dataset objects, each corresponds to one of the netCDF4 groups specified in the SONAR-netCDF4 convention – the convention followed by echopype. The EchoData object can be used to conveniently accesse and explore the echosounder raw data and for calibration and other processing.

For each raw file:

  • Access file directly from S3 via ep.open_raw to create a converted EchoData object in memory

  • Add global and platform attributes to EchoData object

  • Export to a local netCDF file

for s3rawfpath in s3rawfiles:
    raw_fpath = Path(s3rawfpath)
    try:
        # Access file directly from S3 to create a converted EchoData object in memory
        ed = ep.open_raw(
            f"s3://{s3rawfpath}",
            sonar_model='EK60',
            storage_options={'anon': True}
        )
        # Manually populate additional metadata about the dataset and the platform
        # -- SONAR-netCDF4 Top-level Group attributes
        ed.top.attrs['title'] = "2017 Pacific Hake Acoustic Trawl Survey"
        ed.top.attrs['summary'] = (
            f"EK60 raw file {raw_fpath.name} from the {ed.top.attrs['title']}, "
            "converted to a SONAR-netCDF4 file using echopype."
        )
        # -- SONAR-netCDF4 Platform Group attributes
        ed.platform.attrs['platform_type'] = "Research vessel"
        ed.platform.attrs['platform_name'] = "Bell M. Shimada"  # A NOAA ship
        ed.platform.attrs['platform_code_ICES'] = "315"        
        
        # Save to converted netCDF format 
        # Use the same base file name as the raw file but with a ".nc" extension
        ed.to_netcdf(save_path=converted_dpath, overwrite=True)
    except Exception as e:
        print(f"Failed to process raw file {raw_fpath.name}: {e}")
17:19:48  parsing file Summer2017-D20170728-T181619.raw, time of first ping: 2017-Jul-28 18:16:19
17:19:51  saving exports/Summer2017-D20170728-T181619.nc
17:19:56  parsing file Summer2017-D20170728-T184131.raw, time of first ping: 2017-Jul-28 18:41:31
17:19:59  saving exports/Summer2017-D20170728-T184131.nc
17:20:04  parsing file Summer2017-D20170728-T190728.raw, time of first ping: 2017-Jul-28 19:07:28
17:20:07  saving exports/Summer2017-D20170728-T190728.nc
17:20:11  parsing file Summer2017-D20170728-T193459.raw, time of first ping: 2017-Jul-28 19:34:59
17:20:13  saving exports/Summer2017-D20170728-T193459.nc
17:20:16  parsing file Summer2017-D20170728-T195219.raw, time of first ping: 2017-Jul-28 19:52:19
17:20:19  saving exports/Summer2017-D20170728-T195219.nc

Let’s examine the last EchoData object created above, ed. This summary shows a collapsed view the netCDF4 groups that make up the EchoData object, where each group corresponds to an xarray Dataset. The backscatter data is in the Beam group, accessible as ed.beam.

ed
EchoData: standardized raw data from exports/Summer2017-D20170728-T195219.nc
    • <xarray.Dataset>
      Dimensions:  ()
      Data variables:
          *empty*
      Attributes:
          conventions:                 CF-1.7, SONAR-netCDF4-1.0, ACDD-1.3
          keywords:                    EK60
          sonar_convention_authority:  ICES
          sonar_convention_name:       SONAR-netCDF4
          sonar_convention_version:    1.0
          summary:                     EK60 raw file Summer2017-D20170728-T195219.r...
          title:                       2017 Pacific Hake Acoustic Trawl Survey
          date_created:                2017-07-28T19:52:19Z
          survey_name:                 

    • <xarray.Dataset>
      Dimensions:                 (frequency: 3, ping_time: 523)
      Coordinates:
        * frequency               (frequency) float64 1.8e+04 3.8e+04 1.2e+05
        * ping_time               (ping_time) datetime64[ns] 2017-07-28T19:52:19.12...
      Data variables:
          absorption_indicative   (frequency, ping_time) float64 0.002822 ... 0.03259
          sound_speed_indicative  (frequency, ping_time) float64 1.481e+03 ... 1.48...

    • <xarray.Dataset>
      Dimensions:        (location_time: 2769, frequency: 3, ping_time: 523)
      Coordinates:
        * location_time  (location_time) datetime64[ns] 2017-07-28T19:52:22.0009999...
        * frequency      (frequency) float64 1.8e+04 3.8e+04 1.2e+05
        * ping_time      (ping_time) datetime64[ns] 2017-07-28T19:52:19.120000 ... ...
      Data variables:
          latitude       (location_time) float64 dask.array<chunksize=(2500,), meta=np.ndarray>
          longitude      (location_time) float64 dask.array<chunksize=(2500,), meta=np.ndarray>
          sentence_type  (location_time) <U3 dask.array<chunksize=(2500,), meta=np.ndarray>
          pitch          (frequency, ping_time) float64 dask.array<chunksize=(3, 523), meta=np.ndarray>
          roll           (frequency, ping_time) float64 dask.array<chunksize=(3, 523), meta=np.ndarray>
          heave          (frequency, ping_time) float64 dask.array<chunksize=(3, 523), meta=np.ndarray>
          water_level    (frequency, ping_time) float64 dask.array<chunksize=(3, 523), meta=np.ndarray>
      Attributes:
          platform_type:       Research vessel
          platform_name:       Bell M. Shimada
          platform_code_ICES:  315

    • <xarray.Dataset>
      Dimensions:        (location_time: 29194)
      Coordinates:
        * location_time  (location_time) datetime64[ns] 2017-07-28T19:52:19.120000 ...
      Data variables:
          NMEA_datagram  (location_time) <U73 '$SDVLW,5063.975,N,5063.975,N' ... '$...
      Attributes:
          description:  All NMEA sensor datagrams

    • <xarray.Dataset>
      Dimensions:  ()
      Data variables:
          *empty*
      Attributes:
          conversion_software_name:     echopype
          conversion_software_version:  0.5.4
          conversion_time:              2021-10-29T00:20:18Z
          src_filenames:                s3://ncei-wcsd-archive/data/raw/Bell_M._Shi...
          duplicate_ping_times:         0

    • <xarray.Dataset>
      Dimensions:  ()
      Data variables:
          *empty*
      Attributes:
          sonar_manufacturer:      Simrad
          sonar_model:             ER60
          sonar_serial_number:     
          sonar_software_name:     
          sonar_software_version:  2.4.3
          sonar_type:              echosounder

    • <xarray.Dataset>
      Dimensions:                         (frequency: 3, ping_time: 523, range_bin: 3957)
      Coordinates:
        * frequency                       (frequency) float64 1.8e+04 3.8e+04 1.2e+05
        * ping_time                       (ping_time) datetime64[ns] 2017-07-28T19:...
        * range_bin                       (range_bin) int64 0 1 2 3 ... 3954 3955 3956
      Data variables: (12/30)
          channel_id                      (frequency) <U37 'GPT  18 kHz 009072058c8...
          beam_type                       (frequency) int64 1 1 1
          beamwidth_receive_alongship     (frequency) float64 10.9 6.81 6.58
          beamwidth_receive_athwartship   (frequency) float64 10.82 6.85 6.52
          beamwidth_transmit_alongship    (frequency) float64 10.9 6.81 6.58
          beamwidth_transmit_athwartship  (frequency) float64 10.82 6.85 6.52
          ...                              ...
          data_type                       (frequency, ping_time) float64 3.0 ... 3.0
          count                           (frequency, ping_time) float64 3.957e+03 ...
          offset                          (frequency, ping_time) float64 0.0 ... 0.0
          transmit_mode                   (frequency, ping_time) float64 0.0 ... 0.0
          angle_athwartship               (frequency, ping_time, range_bin) float64 ...
          angle_alongship                 (frequency, ping_time, range_bin) float64 ...
      Attributes:
          beam_mode:              vertical
          conversion_equation_t:  type_3

    • <xarray.Dataset>
      Dimensions:           (frequency: 3, pulse_length_bin: 5)
      Coordinates:
        * frequency         (frequency) float64 1.8e+04 3.8e+04 1.2e+05
        * pulse_length_bin  (pulse_length_bin) int64 0 1 2 3 4
      Data variables:
          sa_correction     (frequency, pulse_length_bin) float64 0.0 -0.7 ... -0.3
          gain_correction   (frequency, pulse_length_bin) float64 20.3 22.95 ... 26.55
          pulse_length      (frequency, pulse_length_bin) float64 0.000512 ... 0.00...

print(f"Number of ping times in this EchoData object: {len(ed.beam.ping_time)}")
Number of ping times in this EchoData object: 523

Assemble a list of EchoData object from the converted netCDF files. Note that by default the files are lazy-loaded and only metadata are read into memory, until more operations are executed. In this case, that’s the ep.combine_echodata function, which will combine all the data into a single EchoData object in memory.

ed_list = []
for converted_file in sorted(glob.glob(str(converted_dpath / "*.nc"))):
    ed_list.append(ep.open_converted(converted_file))

combined_ed = ep.combine_echodata(ed_list)
print(f"Number of ping times in the combined EchoData object: {len(combined_ed.beam.ping_time)}")
Number of ping times in the combined EchoData object: 2379

The Provenance group now contains some helpful information about the source files, original ping times prior to reversal corrections (if any), etc.

combined_ed.provenance
<xarray.Dataset>
Dimensions:               (file: 5, echodata_filename: 5, top_attr_key: 9, environment_attr_key: 0, platform_attr_key: 3, nmea_attr_key: 1, provenance_attr_key: 5, sonar_attr_key: 6, beam_attr_key: 2, vendor_attr_key: 0)
Coordinates:
  * echodata_filename     (echodata_filename) <U31 'Summer2017-D20170728-T181...
  * top_attr_key          (top_attr_key) <U26 'sonar_convention_version' ... ...
  * environment_attr_key  (environment_attr_key) float64 
  * platform_attr_key     (platform_attr_key) <U18 'platform_code_ICES' ... '...
  * nmea_attr_key         (nmea_attr_key) <U11 'description'
  * provenance_attr_key   (provenance_attr_key) <U27 'conversion_software_nam...
  * sonar_attr_key        (sonar_attr_key) <U22 'sonar_type' ... 'sonar_softw...
  * beam_attr_key         (beam_attr_key) <U21 'beam_mode' 'conversion_equati...
  * vendor_attr_key       (vendor_attr_key) float64 
Dimensions without coordinates: file
Data variables:
    src_filenames         (file) object exports/Summer2017-D20170728-T181619....
    top_attrs             (echodata_filename, top_attr_key) <U146 '1.0' ... '...
    environment_attrs     (echodata_filename, environment_attr_key) float64 
    platform_attrs        (echodata_filename, platform_attr_key) <U15 '315' ....
    nmea_attrs            (echodata_filename, nmea_attr_key) <U25 'All NMEA s...
    provenance_attrs      (echodata_filename, provenance_attr_key) <U92 'echo...
    sonar_attrs           (echodata_filename, sonar_attr_key) <U11 'echosound...
    beam_attrs            (echodata_filename, beam_attr_key) <U8 'vertical' ....
    vendor_attrs          (echodata_filename, vendor_attr_key) float64 
Attributes:
    conversion_software_name:     echopype
    conversion_software_version:  0.5.4
    conversion_time:              2021-10-29T00:20:26Z

1.4. Extract and plot GPS locations from Platform group

Extract and join the latitude and longitude variables from the Platform group in the combined_ed EchoData object. Convert to a Pandas DataFrame first, then to a GeoPandas GeoDataFrame for convenient viewing and manipulation.

gps_df = combined_ed.platform.latitude.to_dataframe().join(combined_ed.platform.longitude.to_dataframe())
gps_df.head(3)
latitude longitude
location_time
2017-07-28 18:16:21.475999744 43.657532 -124.887015
2017-07-28 18:16:21.635000320 43.657500 -124.887000
2017-07-28 18:16:22.168999936 43.657532 -124.887080
gps_gdf = gpd.GeoDataFrame(
    gps_df,
    geometry=gpd.points_from_xy(gps_df['longitude'], gps_df['latitude']), 
    crs="epsg:4326"
)

Create a cartopy reference map from the point GeoDataFrame, to place the GPS track in its geographical context.

basemap = cimgt.OSM()
_, ax = plt.subplots(
    figsize=(7, 7), subplot_kw={"projection": basemap.crs}
)
bnd = gps_gdf.geometry.bounds
ax.set_extent([bnd.minx.min() - 1, bnd.maxx.max() + 3, 
               bnd.miny.min() - 1, bnd.maxy.max() + 2])
ax.add_image(basemap, 7)
ax.gridlines(draw_labels=True, xformatter=LONGITUDE_FORMATTER, yformatter=LATITUDE_FORMATTER)
gps_gdf.plot(ax=ax, markersize=0.1, color='red', 
             transform=ccrs.PlateCarree());
_images/echopype_tour_30_0.png

1.5. Compute mean volume backscattering strength (\(\text{MVBS}\)) and plot interactive echograms using hvplot

echopype supports basic processing funcionalities including calibration (from raw instrument data records to volume backscattering strength, \(S_V\)), denoising, and computing mean volume backscattering strength, \(\overline{S_V}\) or \(\text{MVBS}\). The EchoData object can be passed into various calibration and preprocessing functions without having to write out any intermediate files.

We’ll calibrate the combined backscatter data to obtain \(S_V\). For EK60 data, by default the function uses environmental (sound speed and absorption) and calibration parameters stored in the data file. Users can optionally specify other parameter choices. \(S_V\) is then binned along range (depth) and ping time to generate \(\text{MVBS}\).

Sv_ds = ep.calibrate.compute_Sv(combined_ed)
MVBS_ds = ep.preprocess.compute_MVBS(
    Sv_ds,
    range_meter_bin=5,  # in meters
    ping_time_bin='20s'  # in seconds
)
MVBS_ds
<xarray.Dataset>
Dimensions:    (ping_time: 391, frequency: 3, range: 150)
Coordinates:
  * ping_time  (ping_time) datetime64[ns] 2017-07-28T18:16:00 ... 2017-07-28T...
  * frequency  (frequency) float64 1.8e+04 3.8e+04 1.2e+05
  * range      (range) float64 0.0 5.0 10.0 15.0 ... 730.0 735.0 740.0 745.0
Data variables:
    Sv         (frequency, ping_time, range) float64 1.503 -73.88 ... -51.14
Attributes:
    binning_mode:          physical units
    range_meter_interval:  5m
    ping_time_interval:    20s

The three frequencies used by the echosounder

MVBS_ds.frequency.values
array([ 18000.,  38000., 120000.])

Generate an interactive plot of the three MVBS echograms, one for each frequency.

MVBS_ds["Sv"].hvplot.image(
    x='ping_time', y='range', 
    color='Sv', rasterize=True, 
    cmap='jet', clim=(-80, -50),
    xlabel='Time (UTC)',
    ylabel='Depth (m)'
).options(width=500, invert_yaxis=True)

1.6. Package versions

import s3fs
print(f"echopype: {ep.__version__}, xarray: {xr.__version__}, geopandas: {gpd.__version__}, "
      f"fsspec: {fsspec.__version__}, s3fs: {s3fs.__version__}")
echopype: 0.5.4, xarray: 0.19.0, geopandas: 0.10.2, fsspec: 2021.10.1, s3fs: 2021.10.1
import datetime
print(f"{datetime.datetime.utcnow()} +00:00")
2021-10-29 00:20:43.268871 +00:00